<template>
  <div class="full-screen-div">
    <div class="login-container">
      <div class="login-title">登录</div>
      <el-form :model="loginForm" @submit="pcLogin">
        <el-form-item label="账号" label-position="left">
          <el-input v-model="loginForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-position="left">
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item class="login-button-item">
          <el-button type="primary" native-type="submit" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
  
  <script setup>
import { ElMessage } from "element-plus";
import { ref } from "vue";
import { getAdminInfo, login } from "../api/pcUser.js";
import { createAdminStore } from "../state/admin.js";
import { getSessionStorageObj } from "../utils/common.js";
import router from "../router/index";

const loginForm = ref({
  account: "",
  password: "",
});

//得到全局数据
const adminStore = createAdminStore();
adminStore.adminInfo;

const pcLogin = async (e) => {
  e?.preventDefault();  // 防止默认表单提交行为
  console.log('登录信息:', loginForm.value);

  if (!loginForm.value.account || !loginForm.value.password) {
    ElMessage({
      type: "warning",
      message: "账号或密码不能为空",
    });
    return;
  }
  try {
    const res = await login(loginForm.value);
    console.log("res", res);
    if (res.flag) {
      const expiresIn = 604800; // 7天
      sessionStorage.setItem("admin_token", res.result);
      sessionStorage.setItem("admin_token_expires_at", Date.now() + expiresIn * 1000); // 确保token存储完成
      
      // 获取用户信息
      const infoRes = await getAdminInfo(loginForm.value.account);
      console.log("infoRes", infoRes);
      
      if(infoRes.flag) {
        // 将用户信息存储到全局状态管理中
        adminStore.setAdminInfo(infoRes.result);
        // 跳转到首页
        await router.push('/layout');
        ElMessage.success('登录成功');
      } else {
        ElMessage({
          type: "error",
          message: "获取用户信息失败：" + infoRes.errorMsg,
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "登录失败！" + res.errorMsg,
      });
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: "登录失败：" + error,
    });
  }
};
</script>
  
  <style scoped>
.full-screen-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #e1efff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  width: 300px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.el-form-item {
  margin-bottom: 20px;
}

.login-button-item {
  display: flex;
  justify-content: center;
  /* 使用flex布局使按钮居中 */
}

.login-button {
  width: 100%;
  /* 使按钮宽度与表单项宽度一致 */
}
</style>